<template>
  <div class="record-container">
    <!-- 搜索和分页控件 -->
    <div class="searchBox">
      <el-form :inline="true" :model="queryParams" class="demoFormInline">
        <el-form-item label="企业名称">
          <el-input v-model="queryParams.companyName" placeholder="请输入企业名称" />
        </el-form-item>
        <!--        <el-form-item label="联系电话">-->
        <!--          <el-input v-model="queryParams.mobile" placeholder="请输入联系电话" />-->
        <!--        </el-form-item>-->
        <el-form-item label="联系电话">
          <el-autocomplete
            v-model="contactSearch"
            :fetch-suggestions="queryContacts"
            placeholder="输入联系电话"
            @select="handleContactSelect"
            style="width: 300px"
          >
            <template #default="{ item }">
              <div class="contact-item">
                <span>{{ item.contactName }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{
                  item.mobile
                }}</span>
              </div>
            </template>
          </el-autocomplete>
        </el-form-item>
        <el-form-item>
          <el-button icon="Search" type="primary" @click="handleSearch">查询</el-button>
          <el-button icon="Refresh" @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 数据表格 -->
    <div class="tableContainer">
      <el-table :data="tableData" border style="width: 100%" v-loading="loading">
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="contactName" label="联系人" min-width="80" />
        <el-table-column prop="gender" label="性别" min-width="50" />
        <el-table-column
          prop="companyName"
          label="关联企业"
          min-width="200"
          show-overflow-tooltip
        />
        <el-table-column prop="mobile" label="联系电话" min-width="120" />
        <el-table-column prop="position" label="头衔/职务" min-width="80" />
        <el-table-column prop="relationship" label="角色" min-width="80" />
        <el-table-column prop="birthday" label="生日" min-width="100">
          <template #default="scope">
            {{ formatDate(scope.row.birthday) }}
          </template>
        </el-table-column>
        <el-table-column prop="intimacyLevel" label="亲密程度" min-width="120" />
        <el-table-column prop="personalHobby" label="个人爱好" min-width="80" />
        <el-table-column prop="contactCount" label="联系次数" min-width="80" />
        <el-table-column
          prop="updateTime"
          label="最后更新时间"
          min-width="150"
          show-overflow-tooltip
        />
        <el-table-column prop="submitter" label="创建人" min-width="80" />
        <el-table-column
          prop="submitTime"
          label="创建时间"
          min-width="150"
          show-overflow-tooltip
        >
          <template #default="scope">
            {{ formatDate2(scope.row.submitTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="scope">
            <el-button type="primary" link @click="editContact(scope.row)"
              >编辑</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页组件 -->
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="fetchData"
    />

    <!-- 编辑联系人弹窗 -->
    <el-dialog
      v-model="editContactDialogVisible"
      title="编辑联系人"
      width="600px"
      :before-close="handleEditContactClose"
    >
      <el-form
        ref="editContactFormRef"
        :model="editContactForm"
        :rules="addContactRules"
        label-width="120px"
        class="info-form"
      >
        <el-form-item label="公司名称" prop="companyName">
          <el-input v-model="editContactForm.companyName" disabled />
        </el-form-item>

        <el-form-item label="联系人姓名" prop="contactName">
          <el-input
            v-model="editContactForm.contactName"
            placeholder="请输入联系人姓名"
          />
        </el-form-item>

        <el-form-item label="职务/头衔" prop="position">
          <el-input v-model="editContactForm.position" placeholder="请输入职务/头衔" />
        </el-form-item>

        <el-form-item label="联系人手机" prop="mobile">
          <el-input v-model="editContactForm.mobile" placeholder="请输入联系人手机" />
        </el-form-item>

        <el-form-item label="微信号" prop="wechat">
          <el-input v-model="editContactForm.wechat" placeholder="请输入微信号" />
        </el-form-item>

        <el-form-item label="联系人籍贯" prop="nativeAddress">
          <el-cascader
            v-model="editContactForm.nativeAddress"
            :options="regionData"
            :props="{ expandTrigger: 'hover' }"
            placeholder="请选择籍贯"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="公司角色" prop="relationship">
          <el-select
            v-model="editContactForm.relationship"
            placeholder="请选择公司角色"
            style="width: 100%"
          >
            <el-option label="法人" value="法人" />
            <el-option label="主办会计" value="主办会计" />
            <el-option label="主要负责人" value="主要负责人" />
            <el-option label="日常联系人" value="日常联系人" />
            <el-option label="租住使用人" value="租住使用人" />
          </el-select>
        </el-form-item>

        <el-form-item label="联系人性别" prop="gender">
          <el-select
            v-model="editContactForm.gender"
            placeholder="请选择性别"
            style="width: 100%"
          >
            <el-option label="男" value="男" />
            <el-option label="女" value="女" />
          </el-select>
        </el-form-item>

        <el-form-item label="联系人学历" prop="education">
          <el-select
            v-model="editContactForm.education"
            placeholder="请选择学历"
            style="width: 100%"
          >
            <el-option label="高中及以下" value="高中及以下" />
            <el-option label="大专" value="大专" />
            <el-option label="本科" value="本科" />
            <el-option label="硕士" value="硕士" />
            <el-option label="博士" value="博士" />
          </el-select>
        </el-form-item>

        <el-form-item label="毕业院校及专业" prop="graduateSchool">
          <el-input
            v-model="editContactForm.graduateSchool"
            placeholder="请输入毕业院校及专业"
          />
        </el-form-item>

        <el-form-item label="联系人年龄" prop="contactAge">
          <el-input
            v-model="editContactForm.contactAge"
            placeholder="具体年龄或者年龄范围 (30-35,35-40, ...)"
          />
        </el-form-item>

        <el-form-item label="联系人生日" prop="birthday">
          <el-date-picker
            v-model="editContactForm.birthday"
            type="date"
            placeholder="选择联系人生日"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="亲密程度" prop="intimacyLevel">
          <el-select
            v-model="editContactForm.intimacyLevel"
            placeholder="请选择亲密程度"
            style="width: 100%"
          >
            <el-option label="初相识" value="初相识" />
            <el-option label="一般关系" value="一般关系" />
            <el-option label="朋友关系" value="朋友关系" />
            <el-option label="好友关系" value="好友关系" />
          </el-select>
        </el-form-item>

        <el-form-item label="个人爱好" prop="personalHobby">
          <el-input
            v-model="editContactForm.personalHobby"
            placeholder="请输入个人爱好"
          />
        </el-form-item>

        <el-form-item label="其他备注" prop="remark">
          <el-input
            v-model="editContactForm.remark"
            placeholder="请输入其他备注"
            type="textarea"
            :rows="4"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleEditContactClose">取消</el-button>
          <el-button type="primary" @click="submitEditContactForm">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { updateContacetInfo } from "@/api/AttractInvestment/customer/index.js";
import { regionData } from "element-china-area-data";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  getFContactInfoList,
  getAllContactInfoList,
} from "@/api/AttractInvestment/contact/index.js";

// 路由
const router = useRouter();
const contactSearch = ref("");
// 查询联系人方法
const queryContacts = async (queryString, cb) => {
  if (!queryString) {
    cb([]);
    return;
  }

  try {
    // 创建临时查询参数来搜索联系人
    const searchParams = {
      ...queryParams,
      pageNum: 1,
      pageSize: 2000000,
    };

    const res = await getFContactInfoList(searchParams);
    if (res && res.code == 200 && res.data && Array.isArray(res.data.records)) {
      // 过滤匹配联系人姓名或电话的记录
      const contacts = res.data.records.filter((contact) => {
        return (
          contact.contactName?.includes(queryString) ||
          contact.mobile?.includes(queryString)
        );
      });

      // 格式化显示数据
      const results = contacts.map((contact) => ({
        value: `${contact.contactName} (${contact.mobile})`,
        contactName: contact.contactName,
        mobile: contact.mobile,
      }));

      cb(results);
    } else {
      cb([]);
    }
  } catch (error) {
    console.error("搜索联系人失败:", error);
    cb([]);
  }
};

// 处理选择联系人事件
const handleContactSelect = (item) => {
  // 将选中的联系电话填入电话输入框
  queryParams.mobile = item.mobile;
  contactSearch.value = item.mobile;
};
// 查询参数
const queryParams = reactive({
  companyName: "",
  contactPhone: "",
  pageNum: 1,
  pageSize: 10,
});

// 表格数据
const tableData = ref([]);
// 分页信息
const total = ref(0);
// 加载状态
const loading = ref(false);
// 添加日期格式化函数，只显示月日
const formatDate = (dateString) => {
  if (!dateString) return "";
  const date = new Date(dateString);
  const year = String(date.getFullYear());
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  return `${year}-${month}-${day}`;
};
// 添加日期格式化函数，创建时间去点 T
const formatDate2 = (dateString) => {
  if (!dateString) return "";
  return dateString.replace("T", " ");
};

//编辑联系人↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
const editContactDialogVisible = ref(false);
// 关闭编辑联系人弹窗
const handleEditContactClose = () => {
  ElMessageBox.confirm("确认放弃修改吗？")
    .then(() => {
      editContactDialogVisible.value = false;
      resetEditContactForm();
    })
    .catch(() => {
      // 用户取消操作
    });
};
// 编辑联系人表单引用
const editContactFormRef = ref(null);
// 编辑联系人函数
// 修改 editContact 函数，添加籍贯回显逻辑
const editContact = (contact) => {
  // 重置表单
  resetEditContactForm();

  // 填充联系人数据
  Object.keys(contact).forEach((key) => {
    if (key in editContactForm) {
      editContactForm[key] = contact[key];
    }
  });
  console.log("contact", contact);

  // 设置公司名称和客户ID
  editContactForm.companyName = contact.companyName;
  editContactForm.customerId = contact.customerId;
  console.log("editContactForm", editContactForm);

  // 处理籍贯回显逻辑
  if (contact.nativeProvince || contact.nativeCity || contact.nativeDistrict) {
    // 根据省市区名称查找对应的编码并设置到级联选择器中
    const addressCodes = [];

    // 查找省编码
    if (contact.nativeProvince) {
      const provinceItem = regionData.find(
        (province) =>
          province.label.includes(contact.nativeProvince) ||
          contact.nativeProvince.includes(province.label)
      );
      if (provinceItem) {
        addressCodes.push(provinceItem.value);

        // 查找市编码
        if (contact.nativeCity) {
          const cityItem = (provinceItem.children || []).find(
            (city) =>
              city.label.includes(contact.nativeCity) ||
              contact.nativeCity.includes(city.label)
          );
          if (cityItem) {
            addressCodes.push(cityItem.value);

            // 查找区编码
            if (contact.nativeDistrict) {
              const districtItem = (cityItem.children || []).find(
                (district) =>
                  district.label.includes(contact.nativeDistrict) ||
                  contact.nativeDistrict.includes(district.label)
              );
              if (districtItem) {
                addressCodes.push(districtItem.value);
              }
            }
          }
        }
      }
    }
    editContactForm.nativeAddress = addressCodes;
  }
  // 设置公司名称和客户ID
  // editContactForm.companyName = currentCompany.companyName;
  // editContactForm.customerId = currentCompany.customerId;
  // 打开编辑弹窗
  editContactDialogVisible.value = true;
};
// 重置编辑联系人表单
function resetEditContactForm() {
  editContactFormRef.value?.resetFields();
  for (let key in editContactForm) {
    if (typeof editContactForm[key] === "string") {
      editContactForm[key] = "";
    } else if (Array.isArray(editContactForm[key])) {
      editContactForm[key] = [];
    } else if (
      typeof editContactForm[key] === "object" &&
      editContactForm[key] !== null
    ) {
      editContactForm[key] = {};
    }
  }
}
// 提交编辑联系人表单
function submitEditContactForm() {
  editContactFormRef.value.validate((valid) => {
    if (valid) {
      processAddressData(editContactForm); // 处理地址数据
      const submitData = { ...editContactForm };

      // 调用API更新联系人信息
      updateContacetInfo(submitData)
        .then((res) => {
          if (res.code === 200) {
            ElMessage.success("联系人更新成功");
            editContactDialogVisible.value = false;
            resetEditContactForm();
            // 刷新联系人列表
            fetchData();
            // handleContactManage();
          } else {
            ElMessage.error(res.msg || "更新失败");
          }
        })
        .catch((err) => {
          console.error("更新联系人失败:", err);
          ElMessage.error("更新联系人失败");
        });
    } else {
      ElMessage.error("请检查输入内容");
    }
  });
}
// 新增联系人表单验证规则
const addContactRules = reactive({
  contactName: [{ required: true, message: "请输入联系人姓名", trigger: "blur" }],
  mobile: [
    { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号码", trigger: "blur" },
  ],
});
// 编辑联系人表单数据（复用新增联系人表单）
const editContactForm = reactive({
  id: "", // 添加联系人ID用于更新
  customerId: "",
  companyName: "",
  contactName: "",
  position: "",
  mobile: "",
  wechat: "",
  nativeAddress: [], // 级联选择器值
  nativeProvince: "",
  nativeCity: "",
  nativeDistrict: "",
  relationship: "",
  gender: "",
  education: "",
  graduateSchool: "",
  contactAge: "",
  birthday: "",
  intimacyLevel: "",
  personalHobby: "",
  remark: "",
});
// 当前公司数据
const currentCompany = reactive({
  department: "",
  companyName: "",
  estimatedTax: "",
  reportTime: "",
  investmentTarget: "",
  estimatedAchievementTime: "",
  businessDeveloper: "",
  id: "",
  customerId: "",
});
// 在提交表单前处理地址数据
const processAddressData = (form) => {
  const address = form.nativeAddress;
  if (!address || !Array.isArray(address) || address.length === 0) {
    return;
  }

  // 使用 regionData 查找对应的中文名称
  const provinceName = findRegionName(address[0]);
  const cityName = address.length >= 2 ? findRegionName(address[1]) : "";
  const districtName = address.length >= 3 ? findRegionName(address[2]) : "";

  form.nativeProvince = provinceName || "";
  form.nativeCity = cityName || "";
  form.nativeDistrict = districtName || "";
};
// 根据编码查找对应的中文名称
const findRegionName = (code) => {
  if (!code || !regionData || !Array.isArray(regionData)) {
    return null;
  }

  // 遍历 regionData 找到对应的名称
  const findName = (data, code) => {
    if (!Array.isArray(data)) return null;

    for (const item of data) {
      if (item.value === code) {
        return item.label;
      }
      if (item.children) {
        const result = findName(item.children, code);
        if (result) {
          return result;
        }
      }
    }
    return null;
  };

  return findName(regionData, code);
};
// 联系人维护
const handleContactManage = () => {
  const customerId = currentCompany.customerId;
  console.log("customerId:", currentCompany);
  console.log("customerId:", customerId);
  if (!customerId) {
    ElMessage.error("无法获取客户ID");
    return;
  }

  getCustomerContact(customerId)
    .then((res) => {
      if (res.code === 200 && Array.isArray(res.data)) {
        // 为每个联系人添加 expanded 属性，默认为 false
        contactList.value = res.data.map((contact) => ({
          ...contact,
          expanded: false,
        }));
      } else {
        contactList.value = [];
      }
      contactDrawerVisible.value = true;
    })
    .catch((err) => {
      console.error("获取联系人失败:", err);
      ElMessage.error("获取联系人失败");
    });
};

//编辑联系人↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑

// 查看企业详情
const viewCompanyDetail = (row) => {
  router.push({
    path: "/lookCompany",
    query: {
      companyId: row.companyId,
    },
  });
};

// 获取数据
const fetchData = async () => {
  loading.value = true;
  try {
    const res = await getFContactInfoList(queryParams);
    if (res && res.code == 200 && res.data) {
      const pageData = res.data;
      // 防御性处理，确保rows为数组
      let rows = [];
      if (Array.isArray(pageData.rows)) {
        rows = pageData.records;
      } else if (
        pageData.records &&
        typeof pageData.records === "object" &&
        typeof pageData.records.length === "number"
      ) {
        rows = Array.from(pageData.records);
      }
      tableData.value = rows;
      total.value = pageData.total || 0;
    } else {
      tableData.value = [];
      total.value = 0;
    }
  } catch (error) {
    console.error("获取企业列表失败:", error);
    tableData.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  queryParams.pageNum = 1;
  fetchData();
};

// 重置表单
const resetForm = () => {
  // 重置查询参数
  Object.assign(queryParams, {
    companyName: "",
    customerId: "",
    mobile: "",
    contactPhone: "",
    industry: "",
    settlementType: "",
    pageNum: 1,
    pageSize: 10,
  });
  contactSearch.value = "";
  fetchData();
};

// 组件挂载时获取数据
onMounted(() => {
  fetchData();
});
</script>

<style scoped>
.record-container {
  padding: 20px;
}

.searchBox {
  margin-bottom: 20px;
}

.tableContainer {
  margin-bottom: 20px;
}
.contact-item {
  line-height: 24px;
  padding: 4px 0;
}
</style>
